<?php

namespace App\Store\Models\Goods;

use App\Common\Services\Common;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\Supply;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class GoodsReplenish extends Model
{
    protected $table = 'site_goods_replenish';
    public $timestamps = false;
    protected $primaryKey = 'id';
    protected $guarded = ['_token'];

    /**
     *获取列表
     */
    public static function getList(Request $request)
    {
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $query = self::with(['storeinfo', 'supply', 'infolist' => function ($query) {
            $query->where('is_del', 1);
        }]);

        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        if($store_ids){//权限控制
            if(is_array($store_ids)){//获取当前权限下的门店
                $query->whereIn('store_id',$store_ids);
            }
            if(is_numeric($store_ids) && intval($store_ids)>0){//获取当前门店下的列表
                $query->where('store_id', intval($store_ids));
            }
        }

        //目标门店
        $store_id = $request['store_id'] ?? 0;
        if ($store_id > 0) {
            $query->where('store_id', $store_id);
        }

        //供应商
        $supply_id = $request['supply_id'] ?? 0;
        if ($supply_id > 0) {
            $query->where('supply_id', $supply_id);
        }

        //订单状态
        $audit_status = $request['audit_status'] ?? 0;
        if ($audit_status > 0) {
            $query->where('audit_status', $audit_status);
        }

        $query->where('is_del', 1)->where('cp_id', $cp_id)->orderBy('create_at', 'desc');

        $isgetall = $request['isgetall'] ?? 0;
        if ($isgetall == 0) {
            $limit = $request->limit ?? 10;
            $list = $query->paginate($limit)->toArray();
            return Common::paginateDataToArray($list);
        } else {
            $list = $query->get()->toArray();
            return ['list' => $list];
        }
    }

    /**
     * 明细表
     */
    public function infolist()
    {
        return $this->hasMany(GoodsReplenishInfolist::class, 'p_id', 'id');
    }

    /**
     * 店铺
     */
    public function storeinfo()
    {
        return $this->hasOne(SiteStore::class, 'id', 'store_id')->select('id', 'store_name');
    }

    /**
     * 供应商
     */
    public function supply()
    {
        return $this->hasOne(Supply::class, 'id', 'supply_id')->select('id', 'supply_name');
    }
}
